﻿using System.Text.RegularExpressions;
using NLog;

namespace TfsGiggle.Core
{
    /// <summary>
    /// Listens to notifications from TFS
    /// </summary>
    public sealed class CheckinService : ICheckinService
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();
        private Regex changesetNumberRegex = new Regex(@"\<Number\>(?<changesetId>[\d]+)\</Number\>");
        private Regex teamProjectCollectionRegex = new Regex(@"pcguid=(?<guid>[0-9abcdef\\-]{36})");

        /// <summary>
        /// Called by TFS
        /// </summary>
        /// <param name="eventXml"></param>
        /// <param name="tfsIdentityXml"></param>
        public void Notify(string eventXml, string tfsIdentityXml)
        {
            _logger.Trace(eventXml);
            var changesetNumberMatch = changesetNumberRegex.Match(eventXml);
            if (changesetNumberMatch != null && changesetNumberMatch.Success)
            {
                var teamProjectCollectionMatch = teamProjectCollectionRegex.Match(eventXml);
                if( teamProjectCollectionMatch != null && teamProjectCollectionMatch.Success )
                {
                    int changesetId;
                    var changeset = changesetNumberMatch.Groups["changesetId"].Value;
                    if (int.TryParse(changeset, out changesetId))
                    {
                        var teamProjectCollectionId = teamProjectCollectionMatch.Groups["guid"].Value;
                        JobManager.Instance.AddJob(teamProjectCollectionId, changesetId);
                    }
                    else
                    {
                        _logger.Warn("Unable to parse changset '{0}' to int", changeset);
                    }
                }
            }
        }
    }
}
